package com.xmall.product.handler.timer;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmall.define.base.Result;
import com.xmall.define.dto.es.EsSkuDto;
import com.xmall.define.request.es.EsSpuSearchRequest;
import com.xmall.product.define.constants.ProductConstants;
import com.xmall.product.define.constants.ProductProperties;
import com.xmall.product.service.ISpuInfoService;
import com.xmall.product.service.other.IMsgService;
import com.xmall.product.service.remote.SearchServiceFeign;
import com.xmall.timer.handler.ITimerTaskHandler;
import com.xmall.utils.XmallUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 商品数据全量同步（新增/更新）
 */
@Slf4j
@Service
public class FullProductDeleteSyncTimerTask implements ITimerTaskHandler {

    @Resource
    private ProductProperties productProperties;

    @Resource
    private SearchServiceFeign searchServiceFeign;

    @Resource
    private IMsgService msgService;

    @Resource
    private ISpuInfoService spuInfoService;

    @Override
    public String key() {
        return ProductConstants.TimerTask.FULL_PRODUCT_DELETE_SYNC_TASK;
    }

    @Override
    public String name() {
        return "商品数据全量同步";
    }

    @Override
    public String desc() {
        return "商品数据全量同步（删除）";
    }

    @Override
    public String cron() {
        return productProperties.getFullProductDeleteSyncCron();
    }

    @Override
    public void execute() {
        try {
            Integer page = 1;
            Integer pageSize = productProperties.getFullProductSyncPageSize();

            // 获取es数据
            Result<Page<EsSkuDto>> result = searchServiceFeign.listPage(new EsSpuSearchRequest(page, pageSize));
            XmallUtils.checkRemoteResult(result);

            // 总页数
            Long pages = result.getData().getPages();
            while (page <= pages) {
                log.info("FullProductDeleteSyncTimerTask sync: {}, currentPage: {}, pageSize: {}, pages: {}, count: {}", DateUtil.formatDateTime(new Date()), page - 1, pageSize, pages, result.getData().getTotal());

                result = searchServiceFeign.listPage(new EsSpuSearchRequest(page, pageSize));
                XmallUtils.checkRemoteResult(result);

                if(CollectionUtil.isEmpty(result.getData().getRecords())) {
                    break;
                }

                result.getData().getRecords().forEach(skuDto -> {
                    if(null == spuInfoService.getById(skuDto.getSpuId())) {
                        msgService.sendProductDeleteMsg(skuDto.getSpuId());
                        log.info("FullProductDeleteSyncTimerTask spuId: {}, need to delete", skuDto.getSpuId());
                    }
                });

                page ++;
                TimeUnit.SECONDS.sleep(productProperties.getFullProductSyncSleepSeconds());
            }
        }catch (Exception e) {
            log.error("FullProductDeleteSyncTimerTask error: {}", e.getMessage());
        }
    }

}
